package com.gimi.cloud.bbp.manage.service.mall.impl;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.transaction.Transactional;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.gimi.cloud.bbp.common.enums.ResponseCodeEnum;
import com.gimi.cloud.bbp.common.exception.MsgException;
import com.gimi.cloud.bbp.common.utils.MyBeanUtils;
import com.gimi.cloud.bbp.commonService.jiguang.JiguangPushUtil;
import com.gimi.cloud.bbp.dao.dao.User.UserDao;
import com.gimi.cloud.bbp.dao.dao.mall.MallMessageDao;
import com.gimi.cloud.bbp.dto.mall.MallMessageDTO;
import com.gimi.cloud.bbp.entity.mall.MallMessage;
import com.gimi.cloud.bbp.manage.service.mall.MallMessageService;

@Service
public class MallMessageServiceImpl implements MallMessageService{

	@Autowired private MallMessageDao dao;
	@Autowired private UserDao userDao;
	@Autowired private JiguangPushUtil jiguangPushUtil;
	
	@Override
	@Transactional
	public void sendMessage(MallMessageDTO dto) throws Exception {
		int i = 0;
		MallMessage mallMessage = new MallMessage();
		MyBeanUtils.copyPropertiesIgnoreNullAndEmptyStr(dto, mallMessage);
		//TODO zfh 需要添加发送人ID
		//设置消息未未读未删除
		mallMessage.setMeStatus(0); //未读
		mallMessage.setMeDelType(0);//删除
		mallMessage.setMeSented(0);//
		for (Integer userId : dto.getUserIds()) {
			mallMessage.setMeReceiveUser(userId);
			i = dao.baseInsert(mallMessage);
			if (i < 1) {
				throw new MsgException(ResponseCodeEnum.UNKNOWN_ERROR);
			}
		}
		
		List<String> list = userDao.getPhoneByUserIds(StringUtils.join(dto.getUserIds(), ","));
		if (list == null || list.isEmpty()) {
			throw new MsgException(ResponseCodeEnum.SUCCESSED);
		}
		String[] strings = list.toArray(new String[] {});
		
		Map<String ,Object> map = new HashMap<>();
		map.put("title", dto.getMeTitle());
		map.put("alert", mallMessage.getMeContent());
		//每次最多推送1000条，超出这分次推送
		for (int j = 0; j < strings.length / 1000 + 1; j++) {
			jiguangPushUtil.pushAlias(mallMessage.getMeContent(), map, dto.get_userId(), Arrays.copyOfRange(strings, j * 1000, (strings.length < (j * 1000 + 999)) ? strings.length : j * 1000 + 999));
		}
	}
}
